import { createRouter, createWebHistory } from "vue-router";
import MainView from "@/views/main/MainView.vue";
import LoginView from "@/views/LoginView.vue";
import Home from "@/views/platformManagement/home/index.vue";
import NotFound from "@/views/404/NotFound.vue";
// 预先获取路由列表
const routerList = JSON.parse(localStorage.getItem("routerList")) || [];
// if (routerList.length) {
//    routerList[0].children.push({
//       path: "/login",
//       title: "登录",
//       icon: "User",
//       type: "menu",
//       disabled: false
//    });
// }
// 固定路由
const fixedRoutes = [
   {
      path: "/login",
      component: LoginView,
      name: "login",
      meta: { requiresAuth: false }, // 不需要认证
   },
   {
      path: "/:catchAll(.*)",
      component: NotFound,
      meta: { requiresAuth: false }, // 不需要认证
   },
];

// 动态路由
const dynamicRoutes = [
   {
      path: "/",
      component: MainView,
      // redirect: { path: localStorage.getItem("routerPath") || "/" }, // 设置默认子路由
      // redirect: { path: routerList[0].children[0].path? routerList[0].children[0].path : "platformManagement/home" }, // 设置默认子路由
      children: [
         {
            path: "platformManagement/Parking/store",
            component: () => import("@/views/platformManagement/Parking/storeView.vue"),
            meta: { requiresAuth: true, breadcrumb: "管家站车位管理" }, // 需要认证
         },
         {
            path: "platformManagement/home",
            name: "home",
            component: Home,
            meta: { requiresAuth: true, breadcrumb: "首页" }, // 需要认证
         },
         {
            path: "platformManagement/systemSettings/loginLogs",
            component: () => import("@/views/platformManagement/systemSettings/loginLogs.vue"),
            meta: { requiresAuth: true, breadcrumb: "登录日志" }, // 需要认证
         },
         {
            path: "platformManagement/systemSettings/organizationalStructure",
            component: () => import("@/views/platformManagement/systemSettings/OrganizationalStructure.vue"),
            meta: { requiresAuth: true, breadcrumb: "组织结构" }, // 需要认证
         },
         {
            path: "platformManagement/systemSettings/personnelManagement",
            component: () => import("@/views/platformManagement/systemSettings/personnelManagement.vue"),
            meta: { requiresAuth: true, breadcrumb: "人员管理" }, // 需要认证
         },
         {
            path: "platformManagement/systemSettings/menuManagement",
            component: () => import("@/views/platformManagement/systemSettings/menuManagement.vue"),
            meta: { requiresAuth: true, breadcrumb: "菜单管理" }, // 需要认证
         },
         {
            path: "platformManagement/systemSettings/permissionUser",
            component: () => import("@/views/platformManagement/systemSettings/permissionUser.vue"),
            meta: { requiresAuth: true, breadcrumb: "用户管理" }, // 需要认证
         },
         {
            path: "platformManagement/systemSettings/rolePermissions",
            component: () => import("@/views/platformManagement/systemSettings/rolePermissions.vue"),
            meta: { requiresAuth: true, breadcrumb: "角色权限" }, // 需要认证
         },
         {
            path: "platformManagement/systemSettings/userActionLog",
            component: () => import("@/views/platformManagement/systemSettings/userActionLog.vue"),
            meta: { requiresAuth: true, breadcrumb: "用户操作日志" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/procurementOverview",
            component: () => import("@/views/platformManagement/procurementManagement/procurementOverview.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购总览" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/supplierManagement",
            component: () => import("@/views/platformManagement/procurementManagement/supplierManagement.vue"),
            meta: { requiresAuth: true, breadcrumb: "供应商管理" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/purchaseOrderManagement",
            component: () => import("@/views/platformManagement/procurementManagement/purchaseOrderManagement.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购订单管理" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/purchaseOrderReview",
            component: () => import("@/views/platformManagement/procurementManagement/purchaseOrderReview.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购订单审核" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/purchaseReturnReview",
            component: () => import("@/views/platformManagement/procurementManagement/purchaseReturnReview.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购退货审核" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/purchaseReturn",
            component: () => import("@/views/platformManagement/procurementManagement/purchaseReturn.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购退货" }, // 需要认证
         },

         {
            path: "platformManagement/procurementManagement/purchaseReport/purchaseDetails",
            component: () => import("@/views/platformManagement/procurementManagement/purchaseReport/purchaseDetails.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购明细" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/purchaseReport/procurementStatistics_suppliers",
            component: () => import("@/views/platformManagement/procurementManagement/purchaseReport/procurementStatistics_suppliers.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购统计（按供应商）" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/purchaseReport/procurementStatistics_products",
            component: () => import("@/views/platformManagement/procurementManagement/purchaseReport/procurementStatistics_products.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购统计（按产品）" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/purchaseReport/purchaseDetails",
            component: () => import("@/views/platformManagement/procurementManagement/purchaseReport/purchaseDetails.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购明细" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/purchaseReport/purchaseReturnDetails",
            component: () => import("@/views/platformManagement/procurementManagement/purchaseReport/purchaseReturnDetails.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购退货明细" }, // 需要认证
         },
         {
            path: "platformManagement/procurementManagement/purchaseReport/returnStatistics_products",
            component: () => import("@/views/platformManagement/procurementManagement/purchaseReport/returnStatistics_products.vue"),
            meta: { requiresAuth: true, breadcrumb: "采购退货统计（按产品）" }, // 需要认证
         },
         {
            path: "/platformManagement/procurementManagement/purchaseReport/returnStatistics_suppliers",
            component: () => import('@/views/platformManagement/procurementManagement/purchaseReport/returnStatistics_suppliers.vue'),
            meta: { requiresAuth: true, breadcrumb: "采购退货统计（按供应商）" }, // 需要认证
         },
         {
            path: "platformManagement/productManagement/product",
            component: () => import("@/views/platformManagement/productManagement/product.vue"),
            meta: { requiresAuth: true, breadcrumb: "产品管理" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/storageIndex",
            component: () => import("@/views/platformManagement/warehouseManagement/storageIndex.vue"),
            meta: { requiresAuth: true, breadcrumb: "仓储管理" }, // 需要认证
         },
         {
            path: "platformManagement/Outbound/Outbound",
            component: () => import("@/views/platformManagement/Outbound/Outbound.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库管理" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/WarehouseInventory",
            component: () => import("@/views/platformManagement/warehouseManagement/WarehouseInventory.vue"),
            meta: { requiresAuth: true, breadcrumb: "产品库存" }, // 需要认证
         },
         {
            path: "platformManagement/Outbound/OutboundManagement",
            component: () => import("@/views/platformManagement/Outbound/OutboundManagement.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库管理" }, // 需要认证
         },
         {
            path: "platformManagement/Outbound/OutboundOrder",
            component: () => import("@/views/platformManagement/Outbound/OutboundOrder.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库订单管理" }, // 需要认证
         },
         {
            path: "platformManagement/Outbound/OutboundAudit",
            component: () => import("@/views/platformManagement/Outbound/OutboundAudit.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库订单审核" }, // 需要认证
         },
         {
            path: "platformManagement/Outbound/OutboundReturnManagement",
            component: () => import("@/views/platformManagement/Outbound/OutboundReturnManagement.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库退货" }, // 需要认证
         },
         {
            path: "platformManagement/Outbound/OutboundReturnReview",
            component: () => import("@/views/platformManagement/Outbound/OutboundReturnReview.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库退货审核" }, // 需要认证
         },
         {
            path: "platformManagement/Outbound/OutboundReport/OutboundDetails",
            component: () => import("@/views/platformManagement/Outbound/OutboundReport/OutboundDetails.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库明细" }, // 需要认证
         },
         {
            path: "platformManagement/Outbound/OutboundReport/OutboundStatisticsList",
            component: () => import("@/views/platformManagement/Outbound/OutboundReport/OutboundStatisticsList.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库统计" }, // 需要认证
         },
         {
            path: "platformManagement/Outbound/OutboundReport/ReturnDetails",
            component: () => import("@/views/platformManagement/Outbound/OutboundReport/ReturnDetails.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库退货明细" }, // 需要认证
         },
         {
            path: "platformManagement/Outbound/OutboundReport/ReturnStatistics",
            component: () => import("@/views/platformManagement/Outbound/OutboundReport/ReturnStatistics.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库退货统计" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/productStorage",
            component: () => import("@/views/platformManagement/warehouseManagement/productStorage.vue"),
            meta: { requiresAuth: true, breadcrumb: "产品入库" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/productStorageSon",
            component: () => import("@/views/platformManagement/warehouseManagement/productStorageSon.vue"),
            meta: { requiresAuth: true, breadcrumb: "子库" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/StorageRecord",
            component: () => import("@/views/platformManagement/warehouseManagement/StorageRecord.vue"),
            meta: { requiresAuth: true, breadcrumb: "入库记录" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/OutboundRecord",
            component: () => import("@/views/platformManagement/warehouseManagement/OutboundRecord.vue"),
            meta: { requiresAuth: true, breadcrumb: "出库记录" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/ProductOutbound",
            component: () => import("@/views/platformManagement/warehouseManagement/ProductOutbound.vue"),
            meta: { requiresAuth: true, breadcrumb: "产品出库" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/InventoryCount",
            component: () => import("@/views/platformManagement/warehouseManagement/InventoryCount.vue"),
            meta: { requiresAuth: true, breadcrumb: "库存盘点" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/StorageRecord",
            component: () => import("@/views/platformManagement/warehouseManagement/StorageRecord.vue"),
            meta: { requiresAuth: true, breadcrumb: "入库记录" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/InventoryReview",
            component: () => import("@/views/platformManagement/warehouseManagement/InventoryReview.vue"),
            meta: { requiresAuth: true, breadcrumb: "库存盘点审核" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/InventoryTransfer",
            component: () => import("@/views/platformManagement/warehouseManagement/InventoryTransfer.vue"),
            meta: { requiresAuth: true, breadcrumb: "库存调拨" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/TransferReview",
            component: () => import("@/views/platformManagement/warehouseManagement/TransferReview.vue"),
            meta: { requiresAuth: true, breadcrumb: "库存调拨审核" }, // 需要认证
         },
         {
            path: "platformManagement/warehouseManagement/InventoryStatistics",
            component: () => import("@/views/platformManagement/warehouseManagement/InventoryStatistics.vue"),
            meta: { requiresAuth: true, breadcrumb: "产品库存统计" }, // 需要认证
         },


         {
            path: "platformManagement/financialManagement/orderPay",
            component: () => import("@/views/platformManagement/financialManagement/orderPay.vue"),
            meta: { requiresAuth: true, breadcrumb: "订单付款" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/paymentApproval",
            component: () => import("@/views/platformManagement/financialManagement/paymentApproval.vue"),
            meta: { requiresAuth: true, breadcrumb: "付款审批" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/paymentRecord",
            component: () => import("@/views/platformManagement/financialManagement/paymentRecord.vue"),
            meta: { requiresAuth: true, breadcrumb: "付款记录" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/orderPayment",
            component: () => import("@/views/platformManagement/financialManagement/orderPayment.vue"),
            meta: { requiresAuth: true, breadcrumb: "订单回款" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/accountsPayable_others",
            component: () => import("@/views/platformManagement/financialManagement/accountsPayable_others.vue"),
            meta: { requiresAuth: true, breadcrumb: "其他付款" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/receivableOther",
            component: () => import("@/views/platformManagement/financialManagement/receivableOther.vue"),
            meta: { requiresAuth: true, breadcrumb: "其他收款" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/collectionRecord",
            component: () => import("@/views/platformManagement/financialManagement/collectionRecord.vue"),
            meta: { requiresAuth: true, breadcrumb: "收款记录" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/financialStatements/accountsReceivable",
            component: () => import("@/views/platformManagement/financialManagement/financialStatements/accountsReceivable.vue"),
            meta: { requiresAuth: true, breadcrumb: "应收账款" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/financialStatements/accountsPayable",
            component: () => import("@/views/platformManagement/financialManagement/financialStatements/accountsPayable.vue"),
            meta: { requiresAuth: true, breadcrumb: "应付账款" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/financialStatements/supplierStatement",
            component: () => import("@/views/platformManagement/financialManagement/financialStatements/supplierStatement.vue"),
            meta: { requiresAuth: true, breadcrumb: "供货商对账单" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/financialStatements/customerStatement",
            component: () => import("@/views/platformManagement/financialManagement/financialStatements/customerStatement.vue"),
            meta: { requiresAuth: true, breadcrumb: "客户对账单" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/basicData/numberingRules",
            component: () => import("@/views/platformManagement/BasicData/numberingRules.vue"),
            meta: { requiresAuth: true, breadcrumb: "编号规则" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/basicData/accountManagement",
            component: () => import("@/views/platformManagement/BasicData/accountManagement.vue"),
            meta: { requiresAuth: true, breadcrumb: "账户管理" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/basicData/unitMeasure",
            component: () => import("@/views/platformManagement/BasicData/unitMeasure.vue"),
            meta: { requiresAuth: true, breadcrumb: "计量单位" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/basicData/customerLevel",
            component: () => import("@/views/platformManagement/BasicData/customerLevel.vue"),
            meta: { requiresAuth: true, breadcrumb: "客户等级" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/basicData/supplierGrade",
            component: () => import("@/views/platformManagement/BasicData/supplierGrade.vue"),
            meta: { requiresAuth: true, breadcrumb: "供应商等级" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/basicData/productManagement",
            component: () => import("@/views/platformManagement/BasicData/productManagement.vue"),
            meta: { requiresAuth: true, breadcrumb: "产品管理(SPU)" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/basicData/consumablesSettings",
            component: () => import("@/views/platformManagement/BasicData/consumablesSettings.vue"),
            meta: { requiresAuth: true, breadcrumb: "耗材设置" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/basicData/ProductAttributeSettings",
            component: () => import("@/views/platformManagement/BasicData/ProductAttributeSettings.vue"),
            meta: { requiresAuth: true, breadcrumb: "产品属性设置" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/basicData/attributeValueManagement",
            component: () => import("@/views/platformManagement/BasicData/attributeValueManagement.vue"),
            meta: { requiresAuth: true, breadcrumb: "属性值管理" }, // 需要认证
         },
         {
            path: "platformManagement/financialManagement/basicData/replenishmentRules",
            component: () => import("@/views/platformManagement/BasicData/ReplenishmentRules.vue"),
            meta: { requiresAuth: true, breadcrumb: "补货规则设置" }, // 需要认证
         },
         {
            path: "404",
            component: () => import("@/views/404/NotFound.vue"),
            meta: { requiresAuth: true, breadcrumb: "404" }, // 需要认证
         }
      ],
      meta: { requiresAuth: true }, // 整个主视图需要认证
   },
];

const router = createRouter({
   history: createWebHistory(),
   routes: [...fixedRoutes, ...dynamicRoutes],
});

router.beforeEach(async (to, from, next) => {
   // 1. 预先加载store（避免动态导入延迟）
   const publicDataStore = (await import("@/stores")).usePublicDataStore();

   // 2. 设置面包屑（登录页除外）
   if (to.path !== "/login") {
      publicDataStore.setBreadcrumbs({
         path: to.path,
         name: to.meta.breadcrumb,
      });
   }

   // 3. 检查路由是否存在
   if (!isRouteExist(to.path)) {
      next();
      return;
   }

   // 4. 根路径重定向
   if (to.path === '/' && localStorage.getItem('routerPath')) {
      next(localStorage.getItem('routerPath'));
      return;
   }

   // 5. 更新当前打开路由
   publicDataStore.setOpenRouter(to.path);

   // 6. 登录状态检查
   const token = localStorage.getItem("token");
   if (!token && to.path !== "/login") {
      next("404");
      return;
   }

   // 7. 放行路由
   next();
});

// 辅助函数：检查路由是否存在
function isRouteExist(path) {
   // 检查主路由
   if (routerList.some(route => route.path === path)) return true;

   // 检查嵌套路由
   const checkNestedRoutes = (routes) => {
      return routes.some(route => {
         if (route.path === path) return true;
         if (route.children) return checkNestedRoutes(route.children);
         return false;
      });
   };

   return checkNestedRoutes(routerList);
}

export default router;
